package io.renren.modules.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.constant.Constant;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.log.entity.SysLogOperationEntity;
import io.renren.modules.security.password.PasswordUtils;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dao.SysDeptDao;
import io.renren.modules.sys.dao.SysRoleDao;
import io.renren.modules.sys.dao.SysTenantDao;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.dto.SysRoleDTO;
import io.renren.modules.sys.dto.SysTenantAccountDTO;
import io.renren.modules.sys.dto.SysTenantDTO;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.entity.SysDeptEntity;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysTenantEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.enums.SuperAdminEnum;
import io.renren.modules.sys.service.*;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 商家入驻管理
 *
 * @author mimao funfind@yeah.net
 * @since 1.0.0 2024-01-13
 */
@Service
public class SysTenantAccountServiceImpl implements SysTenantAccountService {

    @Autowired
    SysTenantDao sysTenantDao;

    @Autowired
    SysUserDao sysUserDao;

    @Autowired
    SysRoleDao sysRoleDao;

    @Autowired
    SysRoleMenuService sysRoleMenuService;

    @Autowired
    SysRoleDataScopeService sysRoleDataScopeService;

    @Autowired
    SysRoleUserService sysRoleUserService;

    @Autowired
    SysDeptDao sysDeptDao;


    @Override
    public SysTenantDTO getTenantAccountInfo(Map<String, Object> params){

        IPage<SysUserEntity> page = getPage(params, Constant.CREATE_DATE, false);

        List<SysUserEntity> tenantList = sysUserDao.getTenantList(params);
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveInfo(SysTenantAccountDTO dto) {

        /**
         * 1.账号绑定租户信息
         * 2.创建角色，绑定对应菜单信息
         * 3.保存用户
         */

        SysLogOperationEntity log = new SysLogOperationEntity();
        UserDetail user = SecurityUser.getUser();
        if (user != null) {
            log.setCreatorName(user.getUsername());
        }

        SysRoleEntity entity = ConvertUtils.sourceToTarget(dto, SysRoleEntity.class);

        SysRoleEntity sysRoleEntity = new SysRoleEntity();
        sysRoleEntity.setTenantId(dto.getTenantId());
        sysRoleEntity.setName(dto.getName()+"管理角色");

        //保存角色
        sysRoleDao.insert(sysRoleEntity);

        Long id = sysRoleEntity.getId();

        //保存角色菜单关系
        sysRoleMenuService.saveOrUpdate(sysRoleEntity.getId(), dto.getMenuIdList());

        //保存角色数据权限关系
        sysRoleDataScopeService.saveOrUpdate(sysRoleEntity.getId(), dto.getDeptIdList());

        SysUserEntity entityUser = ConvertUtils.sourceToTarget(dto, SysUserEntity.class);

        //密码加密
        String password = PasswordUtils.encode(entityUser.getPassword());
        entityUser.setPassword(password);

        //保存用户
        entityUser.setSuperAdmin(SuperAdminEnum.NO.value());
        entityUser.setTenantId(dto.getTenantId());
        entityUser.setUsername(dto.getName());
        entityUser.setStatus(1);
        entityUser.setSuperAdmin(SuperAdminEnum.TENANT.value());
        sysUserDao.insert(entityUser);
        //保存角色用户关系
        sysRoleUserService.saveOrUpdate(entityUser.getId(),Arrays.asList(sysRoleEntity.getId()));

        SysDeptEntity sysDeptEntity = new SysDeptEntity();
        sysDeptEntity.setName(dto.getName()+"管理部门");
        sysDeptEntity.setPids("0");
        sysDeptEntity.setPid(0L);
        sysDeptEntity.setTenantId(dto.getTenantId());
        sysDeptDao.insert(sysDeptEntity);

        return;
    }

    protected IPage<SysUserEntity> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        //分页参数
        long curPage = 1;
        long limit = 10;

        if (params.get(Constant.PAGE) != null) {
            curPage = Long.parseLong((String) params.get(Constant.PAGE));
        }
        if (params.get(Constant.LIMIT) != null) {
            limit = Long.parseLong((String) params.get(Constant.LIMIT));
        }

        //分页对象
        Page<SysUserEntity> page = new Page<>(curPage, limit);

        //分页参数
        params.put(Constant.PAGE, page);

        //排序字段
        String orderField = (String) params.get(Constant.ORDER_FIELD);
        String order = (String) params.get(Constant.ORDER);

        //前端字段排序
        if (StrUtil.isNotBlank(orderField) && StrUtil.isNotBlank(order)) {
            if (Constant.ASC.equalsIgnoreCase(order)) {
                return page.addOrder(OrderItem.asc(orderField));
            } else {
                return page.addOrder(OrderItem.desc(orderField));
            }
        }

        //没有排序字段，则不排序
        if (StrUtil.isBlank(defaultOrderField)) {
            return page;
        }

        //默认排序
        if (isAsc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        } else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }

        return page;
    }
}